/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { useHistory, useLocation } from '@docusaurus/router';
import type { TagType } from '@site/src/data/users';
import { toggleListItem } from '@site/src/utils/jsUtils';
import React from 'react';
import styles from './styles.module.css';

export function readSearchTags(search: string): TagType[] {
  return new URLSearchParams(search).getAll('tags') as TagType[];
}

function replaceSearchTags(search: string, newTags: TagType[]) {
  const searchParams = new URLSearchParams(search);
  searchParams.delete('tags');
  newTags.forEach((tag) => searchParams.append('tags', tag));
  return searchParams.toString();
}

export default function ShowcaseTagSelect({
  tag,
  label,
  icon,
  description,
}: {
  tag: TagType;
  label: string;
  icon: JSX.Element;
  description?: string;
}): JSX.Element {
  const location = useLocation();
  const history = useHistory();
  const tags = readSearchTags(location.search);
  const selected = tags.includes(tag);

  function toggleTag() {
    const newTags = toggleListItem(tags, tag);
    const newSearch = replaceSearchTags(location.search, newTags);
    history.push({
      ...location,
      search: newSearch,
    });
  }

  return (
    <button
      className={styles.checkboxWrapper}
      onClick={toggleTag}
      aria-label={description ?? `Filter by ${label} tag`}>
      <span className={styles.checkbox}>
        <input
          type="checkbox"
          checked={selected}
          onChange={toggleTag}
          className={styles.checkboxInput}
        />
        <span className={styles.checkboxLabel}>{label}</span>
        {icon}
      </span>
    </button>
  );
}
